package com.ckm.controller;

import com.ckm.annotation.LogInfo;
import com.ckm.entity.Student;
import com.ckm.entity.ResponseResult;
import com.ckm.service.StudentService;
import com.ckm.util.ExcelUtils;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Slf4j
@LogInfo
@Validated
@RestController
@RequestMapping("student")
public class StudentController {
    
    @Autowired
    private StudentService studentService;

    /**
     * 添加学生
     * @param studentList 学生信息list
     * @return 成功信息
     */
    @PostMapping("addStudent")
    public ResponseResult addStudent(@RequestBody @Valid List<Student> studentList) {
        studentService.addStudent(studentList);
        return new ResponseResult(200,"添加成功",null);
    }

    @PostMapping("studentExcel")
    public ResponseResult addStudent(@RequestParam("file")MultipartFile file) {
        String[] fileText = {"xls", "xlsx"};
        try {
            InputStream inputStream = ExcelUtils.getInputStream(file, fileText);
            List<Student> list = ExcelUtils.readExcel(inputStream, Student.class);
            studentService.addStudent(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new ResponseResult(200,"添加成功",null);
    }

    /**
     * 更新学生
     * @param student 更新的信息
     * @return 成功信息
     */
    @PutMapping
    public ResponseResult updateStudent(@RequestBody Student student) {
        studentService.updateStudent(student);
        return new ResponseResult(200,"更新成功","");
    }

    /**
     * 删除学生
     * @param id 学生Id
     * @return 成功信息
     */
    @DeleteMapping
    public ResponseResult deleteStudent(@RequestParam(name = "id") Integer id) {
        studentService.deleteStudent(id);
        return new ResponseResult(200,"删除成功","");
    }

    /**
     * 查找学生信息
     * @param student 查找词
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 分页结果集
     */
    @PostMapping("find")
    public ResponseResult findStudent(@RequestBody Student student, @RequestParam(name = "pageNum",defaultValue = "1") int pageNum, @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) {
        return new ResponseResult(200,"查找完毕",studentService.getStudentPage(student,pageNum,pageSize));
    }
}
